package com.lianyi.rabbitdemo;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.LinkedBlockingDeque;

public class MainActivity extends AppCompatActivity {
    private Button button, button2;

    private BlockingDeque<String> queue = new LinkedBlockingDeque<>();
    private Thread publishThread;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button = findViewById(R.id.button);
        button2 = findViewById(R.id.button2);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, ReceiverService.class);
                startService(intent);
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < 10; i++) {
                    publishMessage("adsvfcdaswf" + i);
//                    try {
//                        Thread.sleep(1000);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
                }
            }
        });
        setupConnectionFactory();
        publishToAMQP();
    }

    void publishMessage(String message) {
        try {
            Log.d("发送", "[q] " + message);
            queue.putLast(message);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    ConnectionFactory factory = new ConnectionFactory();

    /**
     * 连接设置
     */
    private void setupConnectionFactory() {
        factory.setHost("192.168.6.102");//主机地址：
        factory.setPort(5672);// 端口号
        factory.setUsername("guest");// 用户名
        factory.setPassword("guest");// 密码
        factory.setVirtualHost("/");
        factory.setRequestedHeartbeat(1);
        factory.setAutomaticRecoveryEnabled(true);// 设置连接恢复
    }

    public void publishToAMQP() {
        publishThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    try {
                        Connection connection = factory.newConnection();
                        Channel ch = connection.createChannel();
//                        ch.queueDeclare("queue", false, false, false, null);
                        ch.confirmSelect();

                        while (true) {
                            String message = queue.takeFirst();
                            try {
                                ch.basicPublish("e1", "send_test", null, message.getBytes());
                                Log.d("111", "[s] " + message);
                                ch.waitForConfirmsOrDie();
                            } catch (Exception e) {
                                Log.d("222", "[f] " + message);
                                queue.putFirst(message);
                                throw e;
                            }
                        }
                    } catch (InterruptedException e) {
                        break;
                    } catch (Exception e) {
                        Log.d("", "Connection broken: " + e.getClass().getName());
                        try {
                            Thread.sleep(5000); //sleep and then try again
                        } catch (InterruptedException e1) {
                            break;
                        }
                    }
                }
            }
        });
        publishThread.start();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Intent intent = new Intent(MainActivity.this, ReceiverService.class);
        stopService(intent);
    }
}
